﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ymatou.SellerApp.Cache;
using Ymatou.SellerApp.Cache.Attrs;

namespace Coments.Service
{
    public class SellerCache
    {
        public static readonly CacheManager CacheManager = new CacheManager();

        public static T Get<T>(CacheType type, string key, Func<T> updater)
        {
            var category = Enum.GetName(typeof(CacheType), type);
            var attr = GetCacheMetta(type);

            return CacheManager.GetOrAdd(category, key, attr.Cache0Expires, attr.Cache1Expires, attr.Cache2Expires,
                updater);
        }

        public static void Set<T>(CacheType type, string key, T value)
        {
            var category = Enum.GetName(typeof(CacheType), type);
            var attr = GetCacheMetta(type);

            CacheManager.Set(category, key, attr.Cache0Expires, attr.Cache1Expires, attr.Cache2Expires, value);
        }

        public static T GetOnly<T>(CacheType type, string key)
        {
            var category = Enum.GetName(typeof(CacheType), type);
            var attr = GetCacheMetta(type);

            return CacheManager.GetOnly<T>(category, key, attr.Cache0Expires, attr.Cache1Expires, attr.Cache2Expires);
        }

        public static void Remove(CacheType type, string key)
        {
            var category = Enum.GetName(typeof(CacheType), type);
            var attr = GetCacheMetta(type);

            CacheManager.Remove(category, key, attr.Cache0Expires, attr.Cache1Expires, attr.Cache2Expires);
        }

        private static AppCacheAttribute GetCacheMetta(CacheType field)
        {
            var type = field.GetType();
            var fieldInfo = type.GetField(Enum.GetName(type, field));
            var attr = fieldInfo.GetCustomAttributes(typeof(AppCacheAttribute), false);
            if (!attr.Any())
                throw new Exception(string.Format("value {0} defined in class {1} does not have a attribute", field,
                    type.Name));

            return (AppCacheAttribute)attr.FirstOrDefault();
        }
    }
}
